package com.snap.awesomeserial;

import android.app.Application;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.multidex.MultiDex;

import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.snap.awesomeserial.logger.ExpDiskLogAdapter;
import com.snap.awesomeserial.logger.OtherDiskLogAdapter;

import org.litepal.LitePal;
import org.litepal.parser.LitePalAttr;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

public class MoleApplication extends Application {

    private static MoleApplication instance;

    public static MoleApplication get() {
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        initLog();
        initUncaughtException();
        LitePal.initialize(this);
        LitePalAttr.getInstance().setStorage(AppConfig.DATABASE_DIRECTORY);
    }

    private void initLog() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  // (Optional) Whether to show thread info or not. Default true
                .methodCount(0)         // (Optional) How many method line to show. Default 2
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, @Nullable String tag) {
                return BuildConfig.DEBUG;
            }
        });
        Logger.addLogAdapter(new OtherDiskLogAdapter());
        Logger.addLogAdapter(new ExpDiskLogAdapter());
    }

    /**
     * init uncaught exception
     */
    private void initUncaughtException() {
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> Logger.e(printExceptionInfo(e)));
    }

    public static String printExceptionInfo(Throwable e) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        e.printStackTrace(printWriter);
        printWriter.close();
        return writer.toString();
    }
}
